package org.csu.onlineedubackend.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.mapper.UserMapper;
import org.csu.onlineedubackend.entity.ChatMessage;
import org.csu.onlineedubackend.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {

    private final Map<Integer, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private ChatService chatService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从session中获取用户ID
        Integer userId = extractUserId(session);
        if (userId != null) {
            userSessions.put(userId, session);
            System.out.println("WebSocket连接已建立：用户ID=" + userId + "，当前在线用户数：" + userSessions.size());
        } else {
            System.out.println("WebSocket连接已建立，但无法获取用户ID，连接可能无效");
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("收到WebSocket消息：" + payload);
        
        try {
            ChatMessage chatMessage = objectMapper.readValue(payload, ChatMessage.class);
            
            // [DEBUG] 打印转换后的对象，检查字段是否正确
            System.out.println("转换后的ChatMessage对象: " + chatMessage.toString());

            // 获取当前用户ID
            Integer userId = extractUserId(session);
            if (userId == null) {
                System.out.println("处理消息失败：无法获取用户ID");
                return;
            }
            
            System.out.println("处理来自用户" + userId + "的消息，会话ID：" + chatMessage.getConversationId());
            
            // 设置发送者ID
            chatMessage.setSenderId(userId);
            
            // 获取发送者信息
            User sender = userMapper.findById(userId);
            if (sender != null) {
                chatMessage.setSenderName(sender.getName());
                System.out.println("发送者：" + sender.getName() + "（ID=" + userId + "）");
            } else {
                System.out.println("警告：找不到ID为" + userId + "的用户信息");
            }
            
            // 处理消息并保存到数据库
            ChatMessage savedMessage = chatService.sendMessage(chatMessage);
            System.out.println("消息已保存到数据库，消息ID：" + savedMessage.getId());
            
            // 获取会话的所有参与者
            List<User> participants = chatService.getConversationParticipants(chatMessage.getConversationId());
            System.out.println("会话参与者数量：" + participants.size());
            
            // 向所有在线参与者发送消息
            for (User participant : participants) {
                if (!participant.getId().equals(userId)) { // 不发给自己
                    WebSocketSession recipientSession = userSessions.get(participant.getId());
                    if (recipientSession != null && recipientSession.isOpen()) {
                        recipientSession.sendMessage(new TextMessage(objectMapper.writeValueAsString(savedMessage)));
                        System.out.println("消息已发送给用户：" + participant.getName() + "（ID=" + participant.getId() + "）");
                    } else {
                        System.out.println("用户" + participant.getName() + "（ID=" + participant.getId() + "）不在线，无法发送消息");
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("处理WebSocket消息时出错：" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Integer userId = extractUserId(session);
        if (userId != null) {
            userSessions.remove(userId);
            System.out.println("WebSocket连接已关闭：用户ID=" + userId + "，关闭状态：" + status + "，当前在线用户数：" + userSessions.size());
        } else {
            System.out.println("WebSocket连接已关闭，但无法获取用户ID，关闭状态：" + status);
        }
    }

    private Integer extractUserId(WebSocketSession session) {
        Map<String, Object> attributes = session.getAttributes();
        if (attributes.containsKey("userId")) {
            return (Integer) attributes.get("userId");
        }
        return null;
    }

    // 发送消息到特定用户
    public void sendMessageToUser(Integer userId, ChatMessage message) {
        WebSocketSession session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(message)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
} 